//
//  HWGameClassifyController.swift
//  HWanGame
//
//  Created by 王昌健 on 2022/3/2.
//  Copyright © 2022 94Wan. All rights reserved.
//

import UIKit
import JXSegmentedView
class HWGameClassifyController: HWBaseViewController {
    var leftTableView:UITableView!
    var rightTableView:UITableView!
    var leftTableViewProtocol = HWGameClassifyLeftProtocol()
    var rightTableViewProtocol = HWGameClassifyRightProtocol()
    var httpManager = HWGameCenterHttpManager()
    var classifyId = ""
    var classifyArray:[HWGameClassifyConfigModel] = []
    var listModel = HWClassifyModel()
    var playerView:CLPlayerView!
    /// 刷新数据
    var refreshButton:UIButton!
    override func viewDidLoad() {
        super.viewDidLoad()
        
        initUI()
        
        initFrame()
        
        loadData()
        
        addRefresh()
        
        addAction()
        
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if playerView != nil {
            self.playerView.destroyPlayer()
        }
    }
    
}
extension HWGameClassifyController {
    private func initUI() -> Void {
        navigationView.isHidden = true
        
        leftTableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        leftTableView.delegate = leftTableViewProtocol
        leftTableView.dataSource = leftTableViewProtocol
        leftTableView.backgroundColor = .white
        leftTableView.separatorStyle = .none
        leftTableView.rowHeight = UITableView.automaticDimension
        leftTableView.estimatedRowHeight = 40
        leftTableView.estimatedSectionHeaderHeight = 0
        leftTableView.estimatedSectionFooterHeight = 0
        leftTableView.showsVerticalScrollIndicator = false
        view.addSubview(leftTableView)
        leftTableView.contentInsetAdjustmentBehavior = .never
//        leftTableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "暂无数据")
//        leftTableView.ly_emptyView.contentViewOffset = -40
        
        rightTableView = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        rightTableView.delegate = rightTableViewProtocol
        rightTableView.dataSource = rightTableViewProtocol
        rightTableView.backgroundColor = .colorWithHexString(hexString: "#FFFFFF")
        rightTableView.separatorStyle = .none
        rightTableView.rowHeight = UITableView.automaticDimension
        rightTableView.estimatedRowHeight = 40
        rightTableView.estimatedSectionHeaderHeight = 0
        rightTableView.estimatedSectionFooterHeight = 0
        rightTableView.showsVerticalScrollIndicator = false
        view.addSubview(rightTableView)
        rightTableView.contentInsetAdjustmentBehavior = .never
        rightTableView.ly_emptyView = LYEmptyView.empty(withImageStr: "", titleStr: "", detailStr: "")
        rightTableView.ly_emptyView.contentViewOffset = -40
        
        if #available(iOS 15.0, *) {
            self.rightTableView.sectionHeaderTopPadding = 0
        } else {
            // Fallback on earlier versions
        }
        
        refreshButton = UIButton(type: .custom)
        refreshButton.frame = CGRect(x: 0, y: 0, width:100*widthScale, height: 40*widthScale)
        refreshButton.setTitle("点击重试", for: .normal)
        refreshButton.setTitleColor(.white, for: .normal)
        refreshButton.titleLabel?.font = .boldSystemFont(ofSize: 14*widthScale)
        refreshButton.layer.cornerRadius = 20*widthScale
        refreshButton.layer.masksToBounds = true
        refreshButton.addTarget(self, action: #selector(refreshButtonClick(_:)), for: .touchUpInside)
        UIColor.gradientColor(view: refreshButton, colors: [UIColor.colorWithHexString(hexString: "#FFB60A").cgColor,UIColor.colorWithHexString(hexString: "#F66A05").cgColor], start: CGPoint(x: 0, y: 0), end: CGPoint(x: 1, y: 0))
        view.addSubview(refreshButton)
        refreshButton.isHidden = true
    }
    
    private func initFrame() -> Void {
        leftTableView.snp.makeConstraints { make in
            make.left.top.bottom.equalToSuperview().priority(.high)
            make.width.equalTo(84*widthScale)
        }
        
        rightTableView.snp.makeConstraints { make in
            make.top.right.bottom.equalToSuperview()
            make.left.equalTo(leftTableView.snp.right)
        }
        
        refreshButton.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.equalTo(100*widthScale)
            make.height.equalTo(40*widthScale)
        }
    }
}

extension HWGameClassifyController:JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }
}

extension HWGameClassifyController {
    func loadData() -> Void {
        httpManager.getGameClassifyConfig { models in
            self.refreshButton.isHidden = true
            self.rightTableView.ly_emptyView.detailStr = "暂无数据"
            self.rightTableView.mj_header?.isHidden = false
            self.rightTableView.mj_footer?.isHidden = false
            if models.count > 0 {
                models[0].isSelected = true
                self.classifyId = models[0].id
                self.getGameList(classifyId: self.classifyId)
                self.classifyArray = models
            }
            self.leftTableViewProtocol.models = models
            self.leftTableView.reloadData()
        } failure: { errorString in
            self.view.showHUD(title: errorString)
            self.rightTableView.ly_emptyView.detailStr = ""
            self.rightTableView.mj_header?.isHidden = true
            self.rightTableView.mj_footer?.isHidden = true
            self.refreshButton.isHidden = false
        }
        
    }
    
    func getGameList(classifyId:String) -> Void {
        httpManager.getClassifyGameList(typeId: classifyId) { model in
            self.rightTableView.mj_header?.endRefreshing()
            self.rightTableView.mj_footer?.endRefreshing()
            self.rightTableViewProtocol.model = model
            self.listModel = model
            self.rightTableView.reloadData()
            if model.game.p > model.game.max_p {
                self.rightTableView.mj_footer?.endRefreshingWithNoMoreData()
            }
        } failure: { errorString in
            self.rightTableView.mj_header?.endRefreshing()
            self.rightTableView.mj_footer?.endRefreshing()
            self.view.showHUD(title: errorString)
        }
    }
    
    func addRefresh() -> () {
        
        rightTableView.mj_header = MJRefreshNormalHeader()
        rightTableView.mj_header?.setRefreshingTarget(self, refreshingAction: #selector(self.loadNewData))
        rightTableView.mj_footer = MJRefreshBackNormalFooter()
        rightTableView.mj_footer?.setRefreshingTarget(self, refreshingAction: #selector(self.loadMoreData))
        rightTableView.mj_header?.isHidden = true
        rightTableView.mj_footer?.isHidden = true
    }
    
    
    @objc func loadNewData() -> () {
        getGameList(classifyId: self.classifyId)
    }
    
    @objc func loadMoreData() -> () {
        rightTableView.mj_footer?.endRefreshing()
        httpManager.getClassifyGameListFooter(typeId: self.classifyId) { model in
            self.rightTableView.mj_header?.endRefreshing()
            self.rightTableView.mj_footer?.endRefreshing()
            if model.game.list.count > 0 {
                for mod in model.game.list {
                    self.listModel.game.list.append(mod)
                }
            }
            if model.game.p > model.game.max_p {
                self.rightTableView.mj_footer?.endRefreshingWithNoMoreData()
            }
            self.rightTableViewProtocol.model = self.listModel
            self.rightTableView.reloadData()
        } failure: { errorString in
            self.rightTableView.mj_header?.endRefreshing()
            self.rightTableView.mj_footer?.endRefreshing()
            self.view.showHUD(title: errorString)
        }
        
    }
    
}


extension HWGameClassifyController {
    func addAction() -> Void {
        
        self.leftTableViewProtocol.didSelectItem = {
            index in
            for mod in self.classifyArray {
                mod.isSelected = false
            }
            self.classifyArray[index].isSelected = true
            self.classifyId = self.classifyArray[index].id
            self.leftTableView.reloadData()
            if index == 0 {
                self.rightTableViewProtocol.isNormal = false
            }else {
                self.rightTableViewProtocol.isNormal = true
            }
            self.getGameList(classifyId: self.classifyId)
        }
        
        self.rightTableViewProtocol.didClickGame = {
            gameId in
            let gameDetail = HWGameDetailController()
            gameDetail.gameId = gameId
            self.navigationController?.pushViewController(gameDetail, animated: true)
        }
        
        self.rightTableViewProtocol.gameImageViewClick = {
            imageView ,model in
            if model.video_url.count > 0 {
                self.playerView = CLPlayerView.init(frame: imageView.frame)
                self.playerView.update { config in
                    config?.topToolBarHiddenType = .small
                    config?.videoFillMode = .resizeAspect
                    config?.autoRotate = false
                }
                self.playerView.url = URL(string: model.video_url)
                imageView.addSubview(self.playerView)
                self.playerView.playVideo()
                self.playerView.endPlay {
                    if self.playerView != nil {
                        self.playerView.destroyPlayer()
                    }
                }
                self.playerView.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
            }else{
                let gameDetail = HWGameDetailController()
                gameDetail.gameId = model.id
                self.navigationController?.pushViewController(gameDetail, animated: true)
            }
        }
        
        self.rightTableViewProtocol.endPlay = {
            if self.playerView != nil {
                self.playerView.destroyPlayer()
            }
        }
        
    }
    
    @objc func refreshButtonClick(_:UIButton) -> Void {
        loadData()
    }
}
